package com.hzlh.oss;

import lombok.AllArgsConstructor;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
public class OssService {

    private ObjectOperations objectOperations;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 上传文件至阿里云OSS，返回绝对路径
     *
     * @param appType
     * @param file
     * @return
     */
    public String uploadLocalFileToOss(String uploadFirstSubDir, String appType, MultipartFile file) {
        return uploadLocalFileToOss(uploadFirstSubDir, appType, file, true);
    }

    /**
     * 上传文件至阿里云OSS
     *
     * @param appType
     * @param file
     * @param absoluteUrl 是否为绝对路径
     * @return
     */
    public String uploadLocalFileToOss(String uploadFirstSubDir, String appType, MultipartFile file, boolean absoluteUrl) {
        return objectOperations.uploadLocalFileToOss(appType, file, absoluteUrl);
    }

    /**
     * 上传文件至阿里云OSS
     *
     * @param appType
     * @param inStream
     * @param fileName 是否为绝对路径
     * @return
     */
    public String uploadFileToOssWithInputStream(String uploadFirstSubDir, String appType, InputStream inStream, String fileName) {
        return objectOperations.uploadLocalFileToOss(appType, inStream, fileName);
    }

    /**
     * 上传文件至阿里云OSS
     *
     * @param appType
     * @param file
     * @return
     */
    public String uploadTmpFileToOss(String uploadFirstSubDir, String appType, File file) {
        return objectOperations.uploadTmpFileToOss(appType, file);
    }

    /**
     * 上传文件至阿里云OSS
     *
     * @param appType
     * @param file
     * @return
     */
    public UploadedFile uploadLocalFileToOss2(String uploadFirstSubDir, String appType, MultipartFile file) {
        String url = objectOperations.uploadLocalFileToOss(appType, file, false);
        UploadedFile uploadedFile = new UploadedFile();
        uploadedFile.setFileUploadedName(url != null ? url.substring(url.lastIndexOf("/")) : "");
        uploadedFile.setUrl(url);
        uploadedFile.setFileOriginalName(file.getOriginalFilename());
        return uploadedFile;
    }

    public UploadedFile uploadStreamToOss(String uploadFirstSubDir, String appType, InputStream inputStream, String fileName) {
        String url = objectOperations.uploadLocalFileToOss(appType, inputStream, fileName);
        UploadedFile uploadedFile = new UploadedFile();
        uploadedFile.setFileUploadedName(fileName);
        uploadedFile.setUrl(url);
        uploadedFile.setFileOriginalName(fileName);
        return uploadedFile;
    }

    /**
     * 不传suffix默认为jpg
     *
     * @param url 图片地址
     */
    public String uploadFileToOssByUrl(String url) throws Exception {
        return uploadFileToOssByUrl(url, "");
    }

    /**
     * 通过url.先上传到oss再返回oss地址
     *
     * @param url    图片地址
     * @param suffix 后缀
     */
    public String uploadFileToOssByUrl(String url, String suffix) throws Exception {
        Object pic = redisTemplate.opsForHash().get("SCRM:PIC", url);
        if (!StringUtils.isEmpty(pic)) {
            return pic.toString();
        }
        File file;
        if (StringUtils.isEmpty(suffix)) {
            file = getFileByUrl(url);
        } else {
            file = getFileByUrl(url, suffix);
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile mockMultipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        String s = uploadLocalFileToOss("pic", "wecom", mockMultipartFile);
        redisTemplate.opsForHash().put("SCRM:PIC", url, s);
        redisTemplate.expire("SCRM:PIC", 7, TimeUnit.DAYS);
        return s;
    }

    /**
     * 上传图片刘文建
     *
     */
    public String uploadFileToOssWithInputStream(String fileType,String suffixName,InputStream file) {
        return objectOperations.uploadFileToOssWithInputStream(fileType, suffixName, file);
    }


  /**
     * 不传suffix默认jpg
     *
     * @param fileUrl url地址
     */
    private File getFileByUrl(String fileUrl) {
        return getFileByUrl(fileUrl, "jpg");
    }

    /**
     * url转file
     *
     * @param fileUrl url地址
     * @param suffix  后缀
     */
    private File getFileByUrl(String fileUrl, String suffix) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = File.createTempFile("pattern", "." + suffix);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (stream != null) stream.close();
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
